<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>CPA数据管理</el-breadcrumb-item>
      <el-breadcrumb-item>产品数据管理</el-breadcrumb-item>
      <el-breadcrumb-item>数据刷新</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-mb15">
<el-form
        inline
        class="m-form--filter"
      >
        <el-form-item>
          <el-date-picker
            class="u-w330"
            size="mini"
            v-model="dateValue"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateChange"
            format="yyyy/MM/dd"
            :picker-options="$store.state.PICKER_OPTIONS"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select
            size="mini"
            class="u-w160"
            v-model="customer_items.model_value"
            :placeholder="customer_items.placeHolder"
            @change="select('1',customer_items.model_value)"
            filterable
          >
            <el-option
              v-for="item in customer_items.options"
              :key="item.customerCode"
              :label="item.name"
              :value="item.customerCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            size="mini"
            v-model="proModelValue"
            :placeholder="pro_items.placeHolder"
            @change="select('2',proModelValue)"
            class="u-w160"
            multiple
            filterable
            collapse-tags
          >
            <el-option
              v-for="item in pro_items.options"
              :key="item.id"
              :label="item.productName"
              :value="item.customerProductCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            size="mini"
            class="u-w160"
            v-model="channelPro_items.model_value"
            :disabled="multipleStatus"
            :placeholder="channelPro_items.placeHolder"
            @change="select('3',channelPro_items.model_value)"
            filterable
          >
            <el-option
              v-for="item in channelPro_items.options"
              :key="item.productPackageCode"
              :label="item.productChannelCode"
              :value="item.productPackageCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            size="mini"
            class="u-w160"
            v-model="channel_items.model_value"
            :disabled="multipleStatus"
            :placeholder="channel_items.placeHolder"
            @change="select('4',channel_items.model_value)"
            filterable
          >
            <el-option
              v-for="item in channel_items.options"
              :key="item.channelProductCode"
              :label="item.channelName"
              :value="item.channelProductCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="businessTypeModel"
            class="u-w160"
            size="mini"
            filterable
            clearable
            placeholder="业务类型"
          >
            <el-option
              v-for="item in BUSINESS_TYPE"
              :key="item.id"
              :label="item.value"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            @click="pageInfo"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </Container>

    <Container>
      <el-form
        inline
        class="m-table--handle"
      >
        <el-form-item>
          <el-button
            size="mini"
            @click.stop="importData"
          >导出数据</el-button>
        </el-form-item>
        <template v-if="activeName === 'updatedRealtimeDatas'">
          <el-form-item>
            <el-button
              size="mini"
              @click="modify"
            >确认修改</el-button>
          </el-form-item>
        </template>
        <CustomTableColumn :columns.sync="tableColumn" />
      </el-form>

      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="待刷新数据"
          name="updatedRealtimeDatas"
        >
        </el-tab-pane>
        <el-tab-pane
          label="已参与结算"
          name="billedRealtimeDatas"
        ></el-tab-pane>
        <el-tab-pane
          label="渠道时间冲突"
          name="errorRealtimeDatas"
        ></el-tab-pane>
      </el-tabs>

      <el-table
        v-loading="loading"
        element-loading-text="拼命加载中"
        :data="tableData"
        border
        stripe
      >
        <el-table-column
          align="center"
          v-for="c in filterTableColumn"
          :key="c.prop"
          :fixed="c.fixed"
          :sortable="c.sortable"
          :prop="c.prop"
          :label="c.label"
          :formatter="c.format"
          :width="c.width"
        >
        </el-table-column>
        <el-table-column
          align="center"
          v-if="activeName=='updatedRealtimeDatas'"
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <span
              class="u-cursor"
              v-if="scope.row.validStatus=='button'"
              @click="checkAllEvent"
            >{{checkAll ? '全选' : '取消全选'}}</span>
            <el-checkbox
              v-else
              v-model="scope.row.validStatus"
            ></el-checkbox>
          </template>
        </el-table-column>
      </el-table>
    </Container>
  </div>
</template>

<script>
import Container from "@/components/container";
import CustomTableColumn from "@/components/custom-table-column";
import BusinessTypeMixin from "@/mixins/business-type";
export default {
  name: "cpa-data-refresh",
  components: {
    Container,
    CustomTableColumn
  },
  mixins: [BusinessTypeMixin],
  data() {
    return {
      proModelValue: [],
      loading: false,
      multipleStatus: false,
      visibleMenuSelectStatus: false,
      checkAll: true,
      tableColumn: [
        {
          fixed: true,
          prop: "dataTime",
          label: "日期",
          sortable: true,
          visible: true
        },
        {
          prop: "customerName",
          label: "客户名称",
          visible: true
        },
        {
          prop: "productName",
          label: "产品名称",
          visible: true
        },
        {
          label: "业务类型",
          prop: "cooperativeMode",
          visible: true
        },
        {
          prop: "productChannelCode",
          label: "上游渠道号",
          visible: true,
          width: 280
        },
        {
          prop: "channelName",
          label: "原渠道名称",
          width: 100,
          visible: true
        },
        {
          prop: "newChannelName",
          label: "新渠道名称",
          width: 100,
          visible: true
        },
        {
          prop: "expectedAct",
          label: "预估激活",
          visible: false
        },
        {
          prop: "settlementAct",
          label: "结算激活",
          visible: true
        },
        {
          prop: "retention",
          label: "留存率",
          visible: false,
          format: function(row) {
            if (row.validStatus != "button") {
              return row.retention + "%";
            } else {
              return "";
            }
          }
        },
        {
          prop: "desc",
          label: "详情",
          visible: false
        }
      ],
      menu_nav: ["CPA数据管理", "实时数据刷新"],
      tableData: [],
      tableDataObj: {},
      dateValue: "",
      customer_items: {
        model_value: "",
        placeHolder: "客户",
        options: []
      },
      pro_items: {
        model_value: "",
        placeHolder: "产品",
        options: []
      },
      channelPro_items: {
        model_value: "",
        placeHolder: "上游渠道号",
        options: []
      },
      channel_items: {
        model_value: "",
        placeHolder: "渠道",
        options: []
      },
      params: {
        type: "",
        val: "",
        startDate: "",
        endDate: ""
      },
      activeName: "updatedRealtimeDatas",
      businessTypeModel: ""
    };
  },
  computed: {
    filterTableColumn() {
      return this.tableColumn.filter(item => item.visible);
    },
    filterTableLabel() {
      return this.filterTableColumn.map(item => item.label);
    },
    filterTableProp() {
      return this.filterTableColumn.map(item => item.prop);
    }
  },
  created() {
    this.customerSelect();
  },
  methods: {
    customerSelect() {
      /*客户*/
      this.$http({
        method: "get",
        url: this.apiUrl.customerSearch,
        params: {
          offset: 1,
          limit: 9999,
          val: ""
        }
      })
        .then(res => {
          if (res.status == 200) {
            var data = res.data;
            this.customer_items.options = data.items;
          }
        })
        .catch(() => {});
    },
    proInfo() {
      /*产品*/
      this.$http({
        method: "get",
        url: this.apiUrl.customerProListLight,
        params: {
          customerCode: this.customer_items.model_value
        }
      })
        .then(res => {
          if (res.status == 200) {
            var data = res.data;
            this.pro_items.options = data.items;
            this.proModelValue = [];
          }
        })
        .catch(() => {});
    },
    channelProInfo() {
      /*上游渠道号*/
      this.$http({
        method: "get",
        url: this.apiUrl.customerProSearch,
        params: {
          offset: 1,
          limit: 9999,
          type: 2,
          code: this.proModelValue.join("|")
        }
      })
        .then(res => {
          if (res.status == 200) {
            var data = res.data;
            this.channelPro_items.options = data.items;
            this.channelPro_items.model_value = "";
          }
        })
        .catch(() => {});
    },
    channelInfo() {
      /*投放渠道*/
      this.$http({
        method: "get",
        url: this.apiUrl.channelProSearch,
        params: {
          offset: 1,
          limit: 9999,
          type: 4,
          code: this.channelPro_items.model_value
        }
      })
        .then(res => {
          if (res.status == 200) {
            var data = res.data;
            this.channel_items.options = data.items;
            this.channel_items.model_value = "";
          }
        })
        .catch(() => {});
    },
    select(type, val) {
      if (val != "") {
        this.params.type = type;
        this.params.val = val;
        switch (type) {
          case "1":
            this.proInfo();
            break;
          case "2":
            this.params.val = val.join("|");
            if (val.length <= 1) {
              this.multipleStatus = false;
              this.channelProInfo();
            } else {
              this.multipleStatus = true;
            }
            break;
          case "3":
            this.channelInfo();
            break;
        }
      }
      //                this.pageInfo();
    },
    pageInfo() {
      if (this.params.startDate == "" || this.params.endDate == "") {
        this.$message({
          type: "info",
          message: "请选择时间"
        });
        return false;
      } else if (this.customer_items.model_value == "") {
        this.$message({
          type: "info",
          message: "请选择客户"
        });
        return false;
      } else if (this.proModelValue.length == 0) {
        this.$message({
          type: "info",
          message: "请选择产品"
        });
        return false;
      }
      this.loading = true;
      this.$http({
        method: "get",
        url: this.apiUrl.realtimeRefresh,
        params: {
          type: this.params.type,
          searchKey: this.params.val,
          sDataTime: this.params.startDate,
          eDataTime: this.params.endDate,
          bizType: this.businessTypeModel
        }
      })
        .then(res => {
          this.loading = false;
          if (res.status === 200) {
            this.checkAll = true;
            let data = res.data;
            if (this.activeName == "updatedRealtimeDatas") {
              if (data.updatedRealtimeDatas.length > 0) {
                data.updatedRealtimeDatas.unshift({ validStatus: "button" });
              }
            }
            this.tableDataObj = data;
            this.tableData = data[this.activeName];
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    changeCheckStatus(e) {
      e.stopPropagation();
      this.visibleMenuSelectStatus = !this.visibleMenuSelectStatus;
    },
    bodyEvent() {
      this.visibleMenuSelectStatus = false;
    },
    preventDefault(e) {
      e.stopPropagation();
    },
    changeInput(e) {
      return e;
    },
    dateChange() {
      this.params.startDate = this.formatDateTime(this.dateValue[0], "y-m-d");
      this.params.endDate = this.formatDateTime(this.dateValue[1], "y-m-d");
    },
    /*全选事件*/
    checkAllEvent() {
      let flag = true;
      for (let item of this.tableData) {
        if (item.validStatus != "button") {
          item.validStatus = this.checkAll;
          flag = false;
        }
      }
      if (flag) return false;
      this.checkAll = !this.checkAll;
    },
    importData() {
      if (this.tableData.length == 0) {
        this.$message({
          type: "info",
          message: "无可导出数据"
        });
        return false;
      }
      let importData = this.tableData;
      let fileName = [
        this.params.startDate,
        this.params.endDate,
        this.customer_items.model_value,
        this.proModelValue.join("|"),
        this.channelPro_items.model_value,
        this.channel_items.model_value,
        this.activeName,
        "实时数据刷新"
      ].join("_");
      this.handleDownload(
        this.filterTableLabel,
        this.filterTableProp,
        importData,
        fileName
      );
    },
    handleClick() {
      this.tableColumn.forEach(item => {
        if (item.prop === "newChannelName") {
          item.visible = this.activeName === "updatedRealtimeDatas";
        }
      });
      this.tableData = this.tableDataObj[this.activeName] || [];
    },
    modify() {
      this.idList = [];
      for (let item of this.tableData) {
        item.validStatus && item.validStatus != "button"
          ? this.idList.push({ id: item.id, channelInfo: item.newChannelName })
          : null;
      }
      if (this.idList.length == 0) {
        this.$message({
          type: "info",
          message: "请选择待刷新数据"
        });
        return false;
      }
      this.$http({
        method: "post",
        url: this.apiUrl.realtimeUpdateChannel,
        data: {
          list: this.idList
        }
      })
        .then(res => {
          if (res.status === 200) {
            if (res.data.status == "2") {
              this.$message({
                type: "success",
                message: "修改成功"
              });
            } else {
              this.$message({
                type: "error",
                message: "修改失败"
              });
            }
          }
        })
        .catch(() => {});
    }
  }
};
</script>
